import styles from './index.less';
import { useState, useEffect } from 'react';
import {
  useIntl,
  history,
  useSelector,
  useDispatch,
  useLocation,
  useModel,
} from 'umi';
import {
  Space,
  Button,
  Form,
  Input,
  Select,
  Row,
  Col,
  Upload,
  message,
  Modal,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import config from '@/config/index';

const { confirm } = Modal;
const { Option } = Select;

import timeZone from '@/data/timeZone';
import { handleAvatarError } from '@/utils';
import { getToken } from '@/utils/auth';

import { rolefn } from '@/data/options';

function GeneralinfoPage() {
  const [form] = Form.useForm();
  const intl = useIntl();
  const dispatch = useDispatch();
  const ulocation = useLocation();

  const roles = rolefn();

  const storeUserInfo = useSelector((state: any) => state.user.userInfo);

  const [userInfo, setUserInfo] = useState(storeUserInfo);

  useEffect(() => {
    if (ulocation.query.id) {
      getPartnerData();
    } else {
      getMyData();
      userStatus();
    }
  }, [ulocation.query.id]);

  const onLogoutWhatasApp = () => {
    request
      .get('/user/logout')
      .then(() => {
        setAuthenticated('N1');
        message.success('logout successfully');
      })
      .catch((err) => {
        message.error(err.message);
      });
  };

  const { authenticated, setAuthenticated, setQrCode } = useModel('hook');

  const onLoginWhatasApp = () => {
    setAuthenticated('N');
  };

  const userStatus = () => {
    request.get('/user/status').then((res) => {
      const { authenticated, qrCode } = res.data;
      setAuthenticated(authenticated);
      setQrCode(qrCode);
    });
  };

  const getMyData = () => {
    request.get('/user/self').then((res) => {
      const { user } = res.data;
      if (user && user.id) {
        localStorage.setItem('uid', user.id);
        localStorage.setItem('userinfo', JSON.stringify(user));
        dispatch({ type: 'user/updateUser', payload: user });

        setUserInfo(user);
        form.setFieldsValue(user);
      }
    });
  };

  const getPartnerData = () => {
    request.get(`/team/${ulocation.query.id}`).then((res) => {
      const { user } = res.data;
      if (user && user.id) {
        setUserInfo(user);
        form.setFieldsValue(user);
      }
    });
  };

  const onFinish = (values: any) => {
    console.log('Success:', values);
    const data = Object.assign({}, userInfo, values);
    const url = ulocation.query.id ? '/team/edit' : '/user/edit';

    request.patch(url, data).then((res) => {
      const { user } = res.data;
      message.success(intl.formatMessage({ id: 'savesuccess' }));
      if (!ulocation.query.id) {
        localStorage.setItem('userinfo', JSON.stringify(user));
        setUserInfo(user);
        history.replace('/settings/generalinfo?v=' + new Date().getTime());
      }
    });
  };

  const uploadProps = {
    name: 'file',
    multiple: true,
    action: config.baseURL + '/system/photoUpload',
    showUploadList: false,
    headers: {
      'Access-Token': getToken(),
    },
    onChange(info: any) {
      const { file, fileList } = info;
      if (file.status !== 'uploading') {
        console.log(file, fileList);
      }
      if (file.status === 'done') {
        const { data } = file.response;
        setUserInfo({
          ...userInfo,
          avatar: data.url,
        });
      } else if (file.status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
  };

  const onRemoveAvatar = () => {
    setUserInfo({
      ...userInfo,
      avatar: '',
    });
  };
  const onResetPassword = () => {
    history.push('/resetPass?source=my');
  };

  const onSave = () => {
    form.submit();
  };

  const onRemoveUser = () => {
    confirm({
      title: 'Confirm delete member?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        request.delete(`/team/${ulocation.query.id}`).then((res) => {
          message.success(intl.formatHTMLMessage({ id: 'removesuccess' }));
          history.goBack();
        });
      },
    });
  };

  const formDefaultValues = {
    yourTimeZone: '105',
    companyTimeZone: '105',
  };

  return (
    <div className={styles.generalinfopage}>
      <div className={styles.head}>
        <h4 className={styles.title}>
          {intl.formatMessage({ id: 'generalinfo' })}
        </h4>
        <Space>
          {userInfo.type === 'captain' &&
          !ulocation.query.id &&
          authenticated === 'Y' ? (
            <Button type="danger" onClick={onLogoutWhatasApp}>
              {intl.formatMessage({ id: 'logoutwhatasapp' })}
            </Button>
          ) : (
            ''
          )}
          {userInfo.type === 'captain' &&
          !ulocation.query.id &&
          authenticated !== 'Y' ? (
            <Button type="primary" onClick={onLoginWhatasApp}>
              {intl.formatMessage({ id: 'loginwhatasapp' })}
            </Button>
          ) : (
            ''
          )}
          {ulocation.query.id ? (
            <Button onClick={() => history.goBack()}>
              {intl.formatMessage({ id: 'goBack' })}
            </Button>
          ) : null}

          {ulocation.query.id ? (
            <Button onClick={onRemoveUser}>
              {intl.formatMessage({ id: 'removeuser' })}
            </Button>
          ) : null}

          <Button type="primary" onClick={onSave}>
            {intl.formatMessage({ id: 'save' })}
          </Button>
        </Space>
      </div>
      <div className={styles.content}>
        <div className={styles.avatarCon}>
          <div className={styles.title}>
            {intl.formatMessage({ id: 'yourphoto' })}
          </div>
          <div className={styles.main}>
            <div className={styles.pic}>
              <img
                src={userInfo.avatar || ''}
                className={styles.avatar}
                alt=""
                onError={handleAvatarError}
              />
            </div>
            <div className={styles.center}>
              <div className={styles.uploadcon}>
                <Upload {...uploadProps}>
                  <div className={styles.uplodtext}>
                    {intl.formatMessage({ id: 'uploadnewphoto' })}
                  </div>
                </Upload>
                <div className={styles.uplodtext} onClick={onRemoveAvatar}>
                  {intl.formatMessage({ id: 'removephoto' })}
                </div>
              </div>
              <div>{intl.formatMessage({ id: 'uploadnewphotoms' })}</div>
              {!ulocation.query.id ? (
                <Button onClick={onResetPassword}>
                  {intl.formatMessage({ id: 'resetpassword' })}
                </Button>
              ) : null}
            </div>
          </div>
        </div>
        <Form
          form={form}
          layout="vertical"
          initialValues={formDefaultValues}
          onFinish={onFinish}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label={intl.formatMessage({ id: 'firstname' })}
                name="name"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'p_e_u_firstname' }),
                  },
                ]}
              >
                <Input
                  placeholder={intl.formatMessage({ id: 'p_e_u_firstname' })}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={intl.formatMessage({ id: 'lastname' })}
                name="lastName"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'p_e_u_lastname' }),
                  },
                ]}
              >
                <Input
                  placeholder={intl.formatMessage({ id: 'p_e_u_lastname' })}
                />
              </Form.Item>
            </Col>
            {/* <Col span={12}>
              <Form.Item
                label={intl.formatMessage({ id: 'position' })}
                name="position"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'p_e_u_position' }),
                  },
                ]}
              >
                <Input
                  placeholder={intl.formatMessage({ id: 'p_e_u_position' })}
                />
              </Form.Item>
            </Col> */}

            <Col span={12}>
              <Form.Item
                label={intl.formatMessage({ id: 'email' })}
                name="email"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'pleaseinputyouremail' }),
                  },
                  {
                    type: 'email',
                    message: intl.formatMessage({
                      id: 'p_e_v_email',
                    }),
                  },
                ]}
              >
                <Input
                  placeholder={intl.formatMessage({
                    id: 'pleaseinputyouremail',
                  })}
                />
              </Form.Item>
            </Col>

            {ulocation.query.id ? (
              <Col span={12}>
                <Form.Item
                  label={intl.formatMessage({ id: 'password' })}
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'pleaseinputyourpassword',
                      }),
                    },
                  ]}
                >
                  <Input.Password
                    placeholder={intl.formatMessage({
                      id: 'pleaseinputyourpassword',
                    })}
                  />
                </Form.Item>
              </Col>
            ) : null}

            {!ulocation.query.id ? (
              <Col span={12}>
                <Form.Item
                  label={intl.formatMessage({ id: 'campanyname' })}
                  name="companyName"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'p_e_u_campanyname' }),
                    },
                  ]}
                >
                  <Input
                    placeholder={intl.formatMessage({
                      id: 'p_e_u_campanyname',
                    })}
                  />
                </Form.Item>
              </Col>
            ) : null}

            <Col span={12}>
              <Form.Item label={intl.formatMessage({ id: 'role' })} name="role">
                <Select disabled>
                  {roles.map((n) => (
                    <Option key={n.value} value={n.value}>
                      {n.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={intl.formatMessage({ id: 'phonenumber' })}
                name="phone"
              >
                <Input
                  placeholder={intl.formatMessage({
                    id: 'pleaseinputyourphonenumber',
                  })}
                />
              </Form.Item>
            </Col>
            {!ulocation.query.id ? (
              <Col span={24}>
                <Form.Item
                  label={intl.formatMessage({ id: 'uniquelink' })}
                  name="url"
                >
                  <Input
                    placeholder={intl.formatMessage({ id: 'p_e_u_uniquelink' })}
                  />
                </Form.Item>
              </Col>
            ) : null}
            {/* {!ulocation.query.id ? (
              <Col span={12}>
                <Form.Item
                  label={intl.formatMessage({ id: 'yourtimezone' })}
                  name="yourTimeZone"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'yourtimezone' }),
                    },
                  ]}
                >
                  <Select showSearch>
                    {timeZone.map((n) => (
                      <Select.Option key={n.value} value={n.value}>
                        {n.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            ) : null}
            {!ulocation.query.id ? (
              <Col span={12}>
                <Form.Item
                  label={intl.formatMessage({ id: 'companytimezone' })}
                  name="companyTimeZone"
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'companytimezone' }),
                    },
                  ]}
                >
                  <Select showSearch>
                    {timeZone.map((n) => (
                      <Select.Option key={n.value} value={n.value}>
                        {n.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            ) : null} */}
          </Row>
        </Form>
      </div>
    </div>
  );
}
GeneralinfoPage.title = '一般资料';
export default GeneralinfoPage;
